package com.heima.schedule.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constant.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.heima.utils.common.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.Minutes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务
     * @param task   任务对象
     * @return
     */
    @Override
    public long addTask(Task task){

        // 1 检验参数
        if(task == null){
            throw new RuntimeException("传入的任务为空");
        }

        // 2 加入到数据库中
        log.info("添加的task的信息为: " + task);
        boolean isSuccess = addTaskInfo(task);

        // 加五分钟作为预设时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,ScheduleConstants.FUTURE_MINUTES_TIME);

        String key = task.getTaskType()+"_"+task.getPriority();

        // 3 加入到redis中
        if(isSuccess){
            // 3.1 如果推送时间小于当前时间,就加入到list中
            if(task.getExecuteTime()<System.currentTimeMillis()){
                cacheService.lLeftPush(ScheduleConstants.TOPIC+key,JSON.toJSONString(task));
            }
            // 3.2 如果推送时间大于当前时间,并且在预期时间内,就加入到zset中
            else if(task.getExecuteTime()<calendar.getTimeInMillis()){
                cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
            }
        }

        return task.getTaskId();
    }


    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskInfo(Task task) {
        boolean flag = false;

        try{
            // 先加入数据到Taskinfo中
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            log.info("添加的taskinfo的信息为: " + taskinfo);
            taskinfoMapper.insert(taskinfo);

            // 加入数据到TaskinfoLogs中
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(ScheduleConstants.VERSION);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            log.info("添加的taskinfoLogs的信息为: " + taskinfoLogs);
            taskinfoLogsMapper.insert(taskinfoLogs);

            // 更新task的taskID
            task.setTaskId(taskinfo.getTaskId());

            flag = true;
        }catch(Exception e){
            log.error("将task任务加入到数据库时出错");
            flag = true;
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId){
        boolean flag = false;

        // 1 修改数据库信息
        Task task = updateTask(taskId, ScheduleConstants.CANCELLED);

        // 2 删除redis中的数据
        long time = task.getExecuteTime();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,ScheduleConstants.FUTURE_MINUTES_TIME);
        long futureTime = calendar.getTime().getTime();

        String key = task.getTaskType()+"_"+task.getPriority();
        if(time < System.currentTimeMillis()){
            // 2.1 删除list数据
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));

        }else if(time<futureTime){
            // 2.2 删除zset数据
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));

        }

        return flag;
    }

    /**
     * 取消任务时修改数据库信息
     * @param taskId
     * @param status
     */
    private Task updateTask(Long taskId, int status) {

        Task task = null;
        try{
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);

            taskinfoMapper.deleteById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            // 转换为task
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("取消任务中更新数据库出错");
            e.printStackTrace();
        }

        return task;
    }

    /**
     * 消费任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task getTask(int type,int priority){
        Task task = null;

        try{
            // 获取并删除redis信息
            String key = type+"_"+priority;
            String s = cacheService.lRightPop(ScheduleConstants.TOPIC + key);

            // 修改数据库信息
            if(s != null){
                task = JSON.parseObject(s, Task.class);
                updateTask(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        }catch (Exception e){
            log.error("消费任务时出错");
            e.printStackTrace();
        }

        return task;
    }


    /**
     * 更新zset中的数据到list中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        String s = cacheService.tryLock("FUTURE_TASK_SYNC", 30 * 1000);

        if(s!=null){
            System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

            // 获取所有未来数据集合的key值
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
            for (String futureKey : futureKeys) { // future_250_250

                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要消费的任务数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (!tasks.isEmpty()) {
                    //将这些任务数据添加到消费者队列中
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }

    }

    /**
     * 将数据库中数据同步到redis中  每五分钟更新一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshRedis(){

        // 1 生成redis中所有缓存
        clearCache();

        //2 查询数据库中所有满足条件数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .le(Taskinfo::getExecuteTime,calendar.getTime()));

        //3 加入到redis中去
        if(taskinfos!=null && taskinfos.size()>0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                addTask(task);
            }
        }

    }

    public void clearCache(){

        // 先查询到所有数据
        Set<String> topics = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futures = cacheService.scan(ScheduleConstants.FUTURE + "*");

        // 删除缓存数据
        cacheService.delete(topics);
        cacheService.delete(futures);

    }



}